<template>
  <div class="m-2 mr-0 overflow-auto bg-white h-full">
    <Spin :spinning="spinning">
      <div class="p-2 flex justify-center">
        <a-button type="primary" class="mr-2" @click="handleCreate"> 新增 </a-button>
        <a-button type="primary" class="mr-2" @click="handleEdit"> 编辑 </a-button>
        <Popconfirm
          placement="top"
          title="确定要删除吗？"
          ok-text="确定"
          cancel-text="取消"
          @confirm="handleDeleteData()"
        >
          <a-button type="primary" class="mr-2"> 删除 </a-button>
        </Popconfirm>
      </div>
      <div class="overflow-auto">
        <BasicTree
          title="角色"
          toolbar
          search
          draggable
          :clickRowToExpand="false"
          v-if="treeData.length > 0"
          :treeData="treeData"
          @select="handleSelect"
          treeKey="code"
          :expandedKeys="expandedKeys"
          :selectedKeys="selectedKeys"
          :defaultExpandAll="defaultExpandAll"
          @drop="handleDrop"
        >
          <template #title="item">
            <Dropdown :trigger="['contextmenu']">
              <template v-if="item.show">
                <Input
                  size="small"
                  style="width: 160px"
                  v-model:value="currentNode.name"
                  @blur="updateType"
                />
              </template>
              <template v-else>
                <span>
                  {{ item.description || item.name }}
                </span>
              </template>
              <template #overlay>
                <div>
                  <Menu
                    @click="({ key: menuKey }) => onContextMenuClick(item.code, menuKey, item)"
                    v-if="item.layer == 1"
                  >
                    <MenuItem key="addType"
                      ><plus-outlined style="color: blue" class="mr-2" />添加</MenuItem
                    >
                    <MenuItem key="editType" v-if="item.value != 1">
                      <edit-outlined style="color: blue" class="mr-2" />重命名
                    </MenuItem>
                    <Popconfirm
                      placement="top"
                      title="确定要删除吗？"
                      ok-text="确定"
                      cancel-text="取消"
                      @confirm="delAction(item.code)"
                    >
                      <MenuItem key="3" v-if="item.value != 1">
                        <delete-outlined style="color: red" class="mr-2" />删除
                      </MenuItem>
                    </Popconfirm>
                  </Menu>
                  <Menu
                    @click="({ key: menuKey }) => onContextMenuClick(item.code, menuKey, item)"
                    v-if="item.layer == 2"
                  >
                    <MenuItem key="edit"
                      ><edit-outlined style="color: blue" class="mr-2" />编辑</MenuItem
                    >
                    <!-- <MenuItem key="user" v-if="item.code != 'member'"
                    ><usergroup-add-outlined style="color: blue" class="mr-2" />用户</MenuItem
                  > -->
                    <MenuItem key="org" v-if="item.code != 'member'"
                      ><home-outlined style="color: blue" class="mr-2" />组织</MenuItem
                    >
                    <MenuItem key="position" v-if="item.code != 'member'"
                      ><inbox-outlined style="color: blue" class="mr-2" />岗位</MenuItem
                    >
                    <MenuItem key="jur"
                      ><link-outlined style="color: blue" class="mr-2" />权限</MenuItem
                    >
                    <MenuItem key="dept" v-if="item.code != 'member'"
                      ><deployment-unit-outlined
                        style="color: blue"
                        class="mr-2"
                      />管理部门</MenuItem
                    >
                    <MenuItem key="menu"
                      ><menu-outlined style="color: blue" class="mr-2" />菜单</MenuItem
                    >
                    <Popconfirm
                      placement="top"
                      title="确定要删除吗？"
                      ok-text="确定"
                      cancel-text="取消"
                      v-if="item.code != 'member'"
                      @confirm="handleDelete(item)"
                    >
                      <MenuItem key="delete">
                        <delete-outlined style="color: red" class="mr-2" />删除
                      </MenuItem>
                    </Popconfirm>
                  </Menu>
                </div>
              </template>
            </Dropdown>
          </template>
        </BasicTree>
      </div>
    </Spin>

    <RoleDrawer @register="registerDrawer" @success="fetch" />
    <UserInfoDrawer @register="userInfoDrawer" />
    <OrgInfoDrawer @register="orgInfoDrawer" />
    <PositionInfo @register="positionInfoDrawer" />
    <JurInfo @register="jurInfoDrawer" />
    <DeptInfo @register="deptInfoDrawer" />
    <MenuInfo @register="menuInfoDrawer" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, onMounted, ref, reactive, unref } from 'vue';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { useModal } from '/@/components/Modal';
  import { Popconfirm, Spin, Dropdown, Menu, Input } from 'ant-design-vue';
  import {
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    UsergroupAddOutlined,
    HomeOutlined,
    InboxOutlined,
    LinkOutlined,
    MenuOutlined,
    DeploymentUnitOutlined,
    CloseOutlined,
    CheckOutlined,
    ProfileOutlined,
  } from '@ant-design/icons-vue';
  import {
    getAdminGetRoleTree,
    getDelRole,
    getAdminOrganizeMoveTreeNode,
    getCreateRoleKind,
    getUpdateRoleKind,
    getDelRoleKind,
  } from '/@/api/system/system';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { checkCanAdminDept } from '/@/api/system/system';
  import { useDrawer } from '/@/components/Drawer';
  import RoleDrawer from './RoleDrawer.vue';
  import UserInfoDrawer from './modules/userInfo/userInfo.vue';
  import OrgInfoDrawer from './modules/orgInfo/orgInfo.vue';
  import PositionInfo from './modules/positionInfo/positionInfo.vue';
  import JurInfo from './modules/jurInfo/jurInfo.vue';
  import DeptInfo from './modules/deptInfo/deptInfo.vue';
  import MenuInfo from './modules/menuInfo/menuInfo.vue';
  import { cloneDeep } from 'lodash-es';
  import { useUserStore } from '/@/store/modules/user';

  export default defineComponent({
    name: 'DeptTreeList',
    components: {
      BasicTree,
      Popconfirm,
      Spin,
      Dropdown,
      Menu,
      MenuItem: Menu.Item,
      PlusOutlined,
      EditOutlined,
      DeleteOutlined,
      RoleDrawer,
      UserInfoDrawer,
      OrgInfoDrawer,
      PositionInfo,
      JurInfo,
      DeptInfo,
      MenuInfo,
      UsergroupAddOutlined,
      HomeOutlined,
      InboxOutlined,
      LinkOutlined,
      MenuOutlined,
      DeploymentUnitOutlined,
      Input,
    },

    emits: ['select', 'drop', 'success'],
    setup(_, { emit }) {
      const treeData = ref<TreeItem[]>([]);
      const oldTreeData = ref<TreeItem[]>([]);
      let expandedKeys = ref<any>([]);
      let selectedKeys = ref([]);
      let dataRef = reactive({});
      const spinning = ref(false);
      const { createMessage } = useMessage();
      const defaultExpandAll = ref(false);
      let deptCount = 0;
      const currentNode = ref<any>({});
      const parentCode = ref('');
      // const memberModel = ref<any>({
      //   code: 'member',
      //   description: '全部用户',
      // });
      // const memberRecord = {
      //   key: memberModel.value.code,
      //   code: memberModel.value.code,
      //   description: memberModel.value.description,
      //   name: memberModel.value.description,
      //   title: memberModel.value.description,
      //   show: false,
      //   isLeaf: true,
      //   layer: 2,
      //   unitCode: 'root',
      //   kind: '1',
      // };
      const userStore = useUserStore();
      const userinfo = userStore.getUserInfo;

      async function fetch() {
        deptCount = 0;
        selectedKeys.value = [];
        treeData.value = [];
        const data = await getAdminGetRoleTree();
        treeData.value = setChildren(data);

        if (userinfo.unitCode == 'root') {
          if (treeData.value && treeData.value.length) {
            // let isMemberInserted = false;
            // treeData.value.forEach((item) => {
            //   if (!isMemberInserted) {
            //     if (item.children && item.children.length) {
            //       item.children.unshift({
            //         ...memberRecord,
            //       });
            //     } else {
            //       item.children = [{ ...memberRecord }];
            //     }
            //     isMemberInserted = true;
            //   }
            // });
          }
        }

        console.log('treeData.value', treeData.value);
        oldTreeData.value = cloneDeep(treeData.value);
        expandedKeys.value = treeData.value.map((item) => item.code);
        dataRef = unref(treeData)[0];

        // 小于30个默认展开
        defaultExpandAll.value = deptCount <= 30;
      }

      function setChildren(node, layer = 1) {
        node.forEach((item) => {
          item.key = item.code;
          item.title = item.description || item.name;
          item.layer = layer;
          item.show = false;
          deptCount++;
          if (item.children && Array.isArray(item.children) && item.children.length > 0) {
            item.isLeaf = false;
            setChildren(item.children, layer + 1);
          } else {
            item.isLeaf = true;
          }
        });
        return node;
      }

      function handleSelect(keys, trc) {
        console.log('trc', trc);
        parentCode.value = '';
        currentNode.value = trc.node;
        if (trc?.node?.dataRef?.layer == 2) {
          // 会切换选中状态
          // selectedKeys.value = keys;

          // 防止切换选中状态
          selectedKeys.value = [trc?.node?.dataRef?.key];
          if (keys.length === 1) {
            dataRef = trc.node.dataRef;
            // delete dataRef['title'];
          } else {
            dataRef = {};
          }
          emit('select', selectedKeys.value[0], dataRef);
        } else if (trc?.node?.dataRef?.layer == 1) {
          parentCode.value = trc.node.dataRef.code;
        }
      }

      function handleGetDataIndex(tree, targetKey) {
        function traverse(nodes, parent = null) {
          for (let index = 0; index < nodes.length; index++) {
            const node = nodes[index];
            if (node.code === targetKey) {
              return {
                node,
                parent,
                index,
              };
            }

            if (node.children) {
              const result = traverse(node.children, node);
              if (result) return result;
            }
          }

          return null;
        }

        return traverse(tree);
      }

      //移动
      function handleDrop(info, current, currentParent, data) {
        let { dropPosition, node } = info;
        console.log('dropPosition', dropPosition);
        // const dropPos = node.pos.split('-'); //层级
        // dropPosition = dropPosition - Number(currentParent.orders)//Number(dropPos[dropPos.length - 1]);
        console.log('handleDrop', {
          dropPosition,
          info,
          current,
          currentParent,
          data,
          treeData: treeData.value,
        });
        const dataTree = handleGetDataIndex(data, current.code);
        console.log('dataTree', dataTree);
        // if (current.code == 'member') {
        //   treeData.value = cloneDeep(oldTreeData.value);
        //   createMessage.warn('全部用户不能拖动');
        //   return;
        // }
        if (dataTree.node.layer == 2 && dataTree.parent.layer != 1) {
          treeData.value = cloneDeep(oldTreeData.value);
          return;
        }
        // if (dataTree.node.layer == 1 && dataTree.parent.layer == 1) {
        //   treeData.value = cloneDeep(oldTreeData.value);
        //   return;
        // }
        let params = {
          code: dataTree.node.code,
          parentCode: dataTree.parent?.code,
          position: dataTree.index,
          layer: dataTree.node.layer,
        };
        console.log('handleDrop-params', params);
        spinning.value = true;
        getAdminOrganizeMoveTreeNode(params).then(() => {
          treeData.value = [];
          fetch();
          emit('success', 1);
          spinning.value = false;
        });
        emit('drop', dropPosition, current, currentParent, data);
      }
      onMounted(() => {
        fetch();
      });

      const [registerDrawer, { openDrawer: openDrawerIndex }] = useDrawer();

      const onContextMenuClick = (treeKey: string, menuKey: string | number, record) => {
        console.log(`treeKey: ${treeKey}, menuKey: ${menuKey},record:`, record);
        console.log(`treeData:`, treeData.value);
        currentNode.value = { ...record };
        delete currentNode.value.title;
        delete currentNode.value.children;
        switch (menuKey) {
          case 'edit':
            handleUpdate(record);
            break;
          case 'user':
            createUserInfoDrawer(record);
            break;
          case 'org':
            createOrgInfoDrawer(record);
            break;
          case 'position':
            createPositionInfoDrawer(record);
            break;
          case 'jur':
            createJurInfoDrawer(record);
            break;
          case 'dept':
            createDeptInfoDrawer(record);
            break;
          case 'menu':
            createMenuInfoDrawer(record);
            break;
          case 'addType':
            createType();
            break;
          case 'editType':
            treeData.value.forEach((item) => {
              if (item.code == record.code) {
                item.show = true;
              } else {
                item.show = false;
              }
            });
            break;
          default:
            break;
        }
      };
      //新增类型
      const createType = async () => {
        let formData = { name: '新建类型' };
        console.log('formData', formData);
        await getCreateRoleKind(formData);
        createMessage.success('操作成功');
        await fetch();
      };
      //类型重命名
      const updateType = async () => {
        console.log('currentNode.value', currentNode.value);
        if (!currentNode.value.code) return;
        delete currentNode.value.title;
        const params = {
          ...currentNode.value.dataRef,
          name: currentNode.value.name,
        };
        Reflect.deleteProperty(params, 'title');
        await getUpdateRoleKind(params);
        createMessage.success('操作成功');
        await fetch();
      };
      //删除类型
      async function delAction(code: string) {
        await getDelRoleKind({ code });
        createMessage.success('操作成功');
        fetch();
        selectedKeys.value = [];
      }
      // 用户
      const [userInfoDrawer, { openDrawer: openDrawerUser }] = useDrawer();
      function createUserInfoDrawer(record) {
        openDrawerUser(true, {
          record,
        });
      }
      //组织
      const [orgInfoDrawer, { openDrawer: openDrawerOrg }] = useDrawer();
      function createOrgInfoDrawer(record) {
        openDrawerOrg(true, {
          record,
        });
      }
      // 岗位
      const [positionInfoDrawer, { openDrawer: openDrawerPosition }] = useDrawer();
      function createPositionInfoDrawer(record) {
        openDrawerPosition(true, {
          record,
        });
      }
      //权限
      const [jurInfoDrawer, { openDrawer: openDrawerJur }] = useDrawer();
      function createJurInfoDrawer(record) {
        openDrawerJur(true, {
          record,
        });
      }
      //部门
      const [deptInfoDrawer, { openDrawer: openDrawerDept }] = useDrawer();
      function createDeptInfoDrawer(record) {
        openDrawerDept(true, {
          record,
        });
      }
      //菜单
      const [menuInfoDrawer, { openDrawer: openDrawerMenu }] = useDrawer();
      function createMenuInfoDrawer(record) {
        openDrawerMenu(true, {
          record,
        });
      }
      async function handleCreate() {
        if (!parentCode.value) {
          createMessage.warning('请先选择分类');
          return;
        }
        openDrawerIndex(true, {
          isUpdate: false,
          showKind: true,
          record: {
            kind: parentCode.value,
          },
        });
      }
      async function handleUpdate(record) {
        console.log('handleUpdate', record);
        openDrawerIndex(true, {
          record: {
            ...record,
            desc: record.description,
            title: '',
          },
          isUpdate: true,
          showKind: true,
        });
      }
      async function handleDelete(record) {
        await getDelRole({ code: record.code }).then(() => {
          fetch();
        });
      }

      const handleEdit = () => {
        if (currentNode.value && currentNode.value.layer == 2) {
          let record = currentNode.value.dataRef;
          console.log('record', record);
          handleUpdate(record);
        } else {
          createMessage.warning('请选择角色编辑');
        }
      };
      const handleDeleteData = () => {
        if (currentNode.value && currentNode.value.layer == 2) {
          handleDelete(currentNode.value);
        } else {
          createMessage.warning('请选择角色删除');
        }
      };

      return {
        fetch,
        treeData,
        handleSelect,
        expandedKeys,
        handleCreate,
        handleDelete,
        handleUpdate,
        selectedKeys,
        handleDrop,
        spinning,
        onContextMenuClick,
        defaultExpandAll,
        registerDrawer,
        userInfoDrawer, //用户
        orgInfoDrawer, //组织
        positionInfoDrawer, //岗位
        jurInfoDrawer, //权限
        deptInfoDrawer, //部门
        menuInfoDrawer, //菜单
        delAction,
        updateType,
        currentNode,
        handleEdit,
        handleDeleteData,
      };
    },
  });
</script>
<style lang="less" scoped>
  .treeList {
    overflow: auto;
    height: calc(100vh - 98px);
  }
</style>
